<template>
    <div class="product-detail-container">
        <div class="detail-content">
            <!-- 商品图片区域 -->
            <div class="product-gallery">
                <div class="main-image">
                    <img :src="mainImageUrl || product.mainImage" :alt="product.title" />
                </div>
                <div class="thumbnail-list">
                    <div v-for="(image, index) in product.images" :key="index" class="thumbnail"
                        :class="{ active: selectedImage === index }" @click="onThumbnailClick(image, index)">
                        <img :src="image" :alt="product.title" />
                    </div>
                </div>
            </div>

            <!-- 商品信息区域 -->
            <div class="product-info">
                <div class="product-header">
                    <div class="product-tags">
                        <span v-for="tag in product.tags as ProductTag[]" :key="tag" class="product-tag" :class="tag">
                            {{ ProductTagLabel[tag] || tag }}
                        </span>
                    </div>
                    <h1 class="product-title">{{ product.title }}</h1>
                </div>

                <div class="price-section">
                    <div class="current-price">
                        <span class="price-symbol">¥</span>
                        <span class="price-value">{{ (selectedSku ? selectedSku.price : product.price) / 100 }}</span>
                    </div>
                    <div v-if="product.marketPrice && product.marketPrice !== product.price" class="original-price">
                        <span class="price-symbol">¥</span>
                        <span class="price-value">{{ product.marketPrice / 100 }}</span>
                    </div>
                </div>

                <!-- 款式选择 -->
                <div v-if="product.saleAttrs && product.saleAttrs.length > 0" class="product-options">
                    <div v-for="attr in product.saleAttrs" :key="attr.key" class="option-group">
                        <label class="option-label">{{ attr.name }}</label>
                        <div class="attr-options">
                            <div v-for="option in attr.content" :key="option.key" class="attr-option"
                                :class="{ active: selectedSkuKey === option.key }" @click="selectSku(option.key)">
                                <span class="option-text">{{ option.text }}</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 数量选择 -->
                <div class="product-options">
                    <div class="option-group">
                        <label class="option-label">数量</label>
                        <div class="quantity-selector">
                            <el-button @click="decreaseQuantity" :disabled="quantity <= 1">-</el-button>
                            <span class="quantity">{{ quantity }}</span>
                            <el-button @click="increaseQuantity">+</el-button>
                        </div>
                    </div>
                </div>

                <div class="action-buttons">
                    <el-button type="primary" size="large" @click="handleBuyNow">
                        立即购买
                    </el-button>
                    <el-button size="large" @click="handleAddToCart">
                        加入购物车
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 商品详情和评论区域 -->
        <div class="detail-tabs-section">
            <!-- Tab 切换 -->
            <div class="detail-tabs">
                <div class="tab-item" :class="{ active: activeTab === 'detail' }" @click="activeTab = 'detail'">
                    商品详情
                </div>
                <div class="tab-item" :class="{ active: activeTab === 'reviews' }" @click="activeTab = 'reviews'">
                    评价 ({{ reviewsCount }})
                </div>
            </div>

            <!-- 商店信息卡片 -->
            <div class="shop-info-card">
                <div class="shop-logo">
                    <img :src="product.shop.icon" :alt="product.shop.ip" />
                </div>
                <div class="shop-info">
                    <div class="shop-name">
                        {{ product.shop.shopName }}
                        <span v-if="product.shop.official" class="official-tag">官方</span>
                        <span v-if="product.shop.cert" class="cert-tag">认证</span>
                    </div>
                    <div class="shop-stats">{{ product.shop.ip }}</div>
                </div>
                <div class="shop-action">
                    <span class="view-all" @click="goToShop">查看全部</span>
                    <el-icon>
                        <ArrowRight />
                    </el-icon>
                </div>
            </div>

            <!-- Tab 内容 -->
            <div class="tab-content">
                <!-- 商品详情 -->
                <div v-if="activeTab === 'detail'" class="detail-content-tab">
                    <div class="detail-images">
                        <div v-for="(image, index) in product.detailImages" :key="index" class="detail-image">
                            <img :src="image" :alt="`详情图${index + 1}`" />
                        </div>
                    </div>
                </div>

                <!-- 评论 -->
                <div v-if="activeTab === 'reviews'" class="reviews-content-tab">
                    <ProductReviews :goods-id="product.goodsId" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import ProductReviews from '@/components/ProductReviews.vue'
import type { ProductTag } from '@/api/shop'
import { ProductTagLabel } from '@/api/shop'
import { getProductDetail } from '@/api/shop'

const route = useRoute()
const router = useRouter()

// 商品数据
const product = ref({
    goodsId: '2028608294324840472576',
    title: '「崩坏：星穹铁道」光锥系列亚克力流沙立牌',
    price: 6800,
    marketPrice: 6800,
    status: 2,
    saleTime: 1753272000,
    haveSku: true,
    mainImage: 'https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/149433e311027bd440c5308731e5f8a2_4642751770306204096.jpeg', // bannerUrl[0] 作为主图
    images: [
        "https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/fba71928875619aae089cd47ce826fb4_7831665216138524295.jpg",
        "https://act-webstatic.mihoyo.com/upload/mall/2025/06/11/40a7829bf698099cfc25f0616bbe9c76_3146889449930295136.jpg",
        "https://act-webstatic.mihoyo.com/upload/mall/2025/06/11/6b7a3adadeaf13131b7bec9b8a9fe790_5528926840060211236.jpg",
        "https://act-webstatic.mihoyo.com/upload/mall/2025/04/28/90519f131d68edf6f5d1c386d6963508_6909338589741336549.jpg",
        "https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/2ab3475e17190a81a6cc73688ca080ed_4433694195853194354.jpg"
    ],
    brand: '崩坏：星穹铁道',
    brandIcon: 'https://webstatic.mihoyo.com/upload/static-resource/2023/04/19/8bd2b680b62364553e8990fbcf3b72b0_3834262096164886047.png',
    tags: ['recommended', 'new'] as ProductTag[],
    detailImages: [
        "https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/b7a306e09fc9b0b4a681122e779ed285_7941137236355704577.jpg",
        "https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/73fabb7a9086d09f4b4d0414185d56b1_3769944463178526143.jpg",
        "https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/cd7764398b353810c1203143354a7844_1934066226442819606.jpg",
        "https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/a090a4d35094e815ebd3695993c8ee67_1405420394399310966.jpg",
        "https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/a40bb2b18be6aef387028d94a2fe923a_7867910601904560627.jpg"
    ],
    saleAttrs: [
        {
            name: '款式',
            content: [
                {
                    isChose: true,
                    text: '银河铁道之夜',
                    key: 'c85882c66923b9a8',
                    imgUrl: ''
                },
                {
                    isChose: true,
                    text: '黎明恰如此燃烧【二批次预售】',
                    key: 'd3cb4ecb03d3da66',
                    imgUrl: 'https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/149433e311027bd440c5308731e5f8a2_2642533864955498787.jpeg'
                }
            ],
            isOpen: false,
            key: 'kcd81353e2b5b177'
        }
    ],
    shop: {
        shopCode: 'xqtd',
        shopName: '货全杂货铺',
        icon: 'https://mock-url',
        cert: true,
        official: true,
        selfSupportCert: false,
        ip: '崩坏：星穹铁道'
    }
})

const selectedImage = ref(0)
const mainImageUrl = ref<string>('')
const quantity = ref(1)
const activeTab = ref('detail')
const selectedSkuKey = ref('')
const selectedSku = ref(null)

// 方法
const decreaseQuantity = () => {
    if (quantity.value > 1) {
        quantity.value--
    }
}

const increaseQuantity = () => {
    quantity.value++
}

const handleBuyNow = () => {
    ElMessage.success(`立即购买 ${quantity.value} 件商品`)
}

const handleAddToCart = () => {
    ElMessage.success(`已添加 ${quantity.value} 件商品到购物车`)
}

const goToShop = () => {
    router.push('/shop')
}

const setMainImage = (url: string) => {
    mainImageUrl.value = url
}

const onThumbnailClick = (url: string, index: number) => {
    selectedImage.value = index
    setMainImage(url)
}

const selectSku = (skuKey) => {
    selectedSkuKey.value = skuKey
    const skus: any = (product.value as any).skus
    if (skus && typeof skus === 'object') {
        selectedSku.value = skus[skuKey] ?? null
    } else {
        selectedSku.value = null
    }
    // 根据所选SKU匹配其在销售属性中的图片并更新主图
    try {
        for (const attr of product.value.saleAttrs || []) {
            const match = (attr.content || []).find((opt: any) => opt.key === skuKey)
            if (match && match.imgUrl) {
                setMainImage(match.imgUrl)
                break
            }
        }
    } catch (e) {
        // 安全兜底，不影响选择逻辑
    }
}

// 计算属性：获取当前选中的SKU
const currentSku = computed(() => {
    if (selectedSkuKey.value && product.value.skus[selectedSkuKey.value]) {
        return product.value.skus[selectedSkuKey.value]
    }
    return null
})

// 计算属性：评论数量格式化
const reviewsCount = computed(() => {
    const count = 6071 // 这里可以从API获取实际数量
    if (count >= 10000) {
        return (count / 10000).toFixed(1) + '万+'
    }
    return count.toString()
})

const getDetail = async (goodsId: string) => {
    try {
        const data: any = await getProductDetail({ goodsId })
        if (data) {
            product.value = {}
            product.value = data
        }
        setMainImage(product.value.mainImage)
    } catch (error) {
        // 保留默认数据并提示
        console.error('获取商品详情失败', error)
        ElMessage.warning('获取商品详情失败，已展示默认数据')
    }
}

onMounted(() => {
    const goodsId = String(route.params.id || product.value.goodsId)
    getDetail(goodsId)
})
</script>

<style scoped>
.product-detail-container {
    margin: 0 20px;
    background: #fff;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

.detail-content {
    display: flex;
    gap: 48px;
    align-items: stretch;
    margin-bottom: 48px;
}

/* 商品图片区域 */
.product-gallery {
    position: relative;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
}

.main-image {
    width: 560px;
    height: 560px;
    overflow: hidden;
    margin-bottom: 16px;
    border: 1px solid #e9ecef;
    flex-shrink: 0;
}

.main-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.thumbnail-list {
    display: flex;
    gap: 12px;
    width: 560px;
    justify-content: flex-start;
    flex-shrink: 0;
}

.thumbnail {
    width: calc((100% - 48px) / 5);
    aspect-ratio: 1 / 1;
    overflow: hidden;
    cursor: pointer;
    border: 2px solid transparent;
    transition: all 0.3s ease;
}

.thumbnail.active {
    border-color: #409eff;
}

.thumbnail:hover {
    border-color: #409eff;
}

.thumbnail img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

/* 商品信息区域 */
.product-info {
    padding: 0 24px;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
}

.product-header {
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
}

.brand-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
}

.brand-icon {
    width: 30px;
    height: 30px;
    border-radius: 6px;
    overflow: hidden;
}

.brand-icon img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.brand-name {
    font-size: 14px;
    color: #666;
}

.product-title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 0;
    line-height: 1.4;
}

.product-tags {
    display: flex;
    gap: 8px;
    margin-bottom: 0;
}

.product-tag {
    padding: 4px 12px;
    border-radius: 16px;
    font-size: 12px;
    font-weight: 500;
    color: #fff;
}

.product-tag.recommended {
    background: #ff9500;
}

.product-tag.hot {
    background: #ff4d4f;
}

.product-tag.new {
    background: #52c41a;
}

.product-tag.limited {
    background: #6f42c1;
}

.price-section {
    margin-bottom: 24px;
}

.current-price {
    display: flex;
    align-items: baseline;
    gap: 4px;
    margin-bottom: 8px;
}

.price-symbol {
    font-size: 18px;
    color: #ff4d4f;
    font-weight: 500;
}

.price-value {
    font-size: 32px;
    color: #ff4d4f;
    font-weight: 700;
}

.original-price {
    display: flex;
    align-items: baseline;
    gap: 2px;
}

.original-price .price-symbol,
.original-price .price-value {
    font-size: 14px;
    color: #999;
    text-decoration: line-through;
}

.product-status {
    margin-bottom: 24px;
}

.status-tag {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 16px;
    font-size: 12px;
    font-weight: 500;
    color: #fff;
}

.status-tag.not-on-sale {
    background: #999;
}

.status-tag.pre-sale {
    background: #ff9500;
}

.status-tag.on-sale {
    background: #52c41a;
}

.status-tag.off-sale {
    background: #ff4d4f;
}

.product-options {
    margin-bottom: 32px;
}

.option-group {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    margin-bottom: 16px;
    min-height: 40px;
}

.attr-options {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    flex: 1;
}

.attr-option {
    position: relative;
    padding: 8px 16px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
    background: #fff;
}

.attr-option:hover {
    border-color: #409eff;
    color: #409eff;
}

.attr-option.active {
    border-color: #ff4d4f;
    background: #fff;
    color: #ff4d4f;
}

.option-text {
    font-size: 14px;
    white-space: nowrap;
}

.option-label {
    font-size: 14px;
    color: #666;
    min-width: 60px;
    padding-top: 8px;
    flex-shrink: 0;
}

.quantity-selector {
    display: flex;
    align-items: center;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    overflow: hidden;
}

.quantity-selector .el-button {
    border: none;
    border-radius: 0;
    width: 36px;
    height: 36px;
}

.quantity {
    padding: 0 16px;
    min-width: 60px;
    text-align: center;
    font-size: 14px;
    color: #333;
}

.action-buttons {
    display: flex;
    gap: 16px;
    margin-bottom: 32px;
    flex-shrink: 0;
}

.action-buttons .el-button {
    flex: 1;
    height: 48px;
    font-size: 16px;
}

.product-description,
.product-specs {
    margin-bottom: 24px;
    flex: 1;
}

.product-specs {
    margin-bottom: 0;
}

.product-description h3,
.product-specs h3 {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
}

.product-description p {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
}

.product-specs ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.product-specs li {
    display: flex;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
    font-size: 14px;
}

.spec-name {
    color: #666;
    min-width: 80px;
}

.spec-value {
    color: #333;
    flex: 1;
}

/* 商品详情和评论区域 */
.detail-tabs-section {
    background: #fff;
    border-top: 1px solid #e9ecef;
}

.detail-tabs {
    display: flex;
    border-bottom: 1px solid #e9ecef;
    background: #fff;
}

.tab-item {
    padding: 16px 24px;
    cursor: pointer;
    font-size: 16px;
    color: #666;
    border-bottom: 2px solid transparent;
    transition: all 0.3s ease;
}

.tab-item:hover {
    color: #409eff;
}

.tab-item.active {
    color: #ff4d4f;
    border-bottom-color: #ff4d4f;
}

/* 商店信息卡片 */
.shop-info-card {
    display: flex;
    align-items: center;
    padding: 20px;
    margin: 20px;
    background: linear-gradient(135deg, #f8f9fa 0%, #fff 100%);
    border-radius: 8px;
    border: 1px solid #e9ecef;
}

.shop-logo {
    width: 48px;
    height: 48px;
    margin-right: 16px;
    overflow: hidden;
}

.shop-logo img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.shop-info {
    flex: 1;
}

.shop-name {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 4px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.official-tag {
    background: #ff9500;
    color: #fff;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.cert-tag {
    background: #52c41a;
    color: #fff;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.shop-stats {
    font-size: 14px;
    color: #666;
}

.shop-action {
    display: flex;
    align-items: center;
    gap: 4px;
    cursor: pointer;
    color: #409eff;
    font-size: 14px;
}

.view-all:hover {
    text-decoration: underline;
}

/* Tab 内容 */
.tab-content {
    padding: 0 20px 20px;
}

.detail-content-tab {
    margin-top: 20px;
}

.detail-images {
    display: flex;
    flex-direction: column;
    gap: 16px;
    align-items: center;
}

.detail-image {
    width: 80%;
    max-width: 1000px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.detail-image img {
    width: 100%;
    height: auto;
    display: block;
}

.reviews-content-tab {
    margin-top: 20px;
    text-align: center;
}

.reviews-placeholder {
    color: #999;
    font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .detail-content {
        flex-direction: column;
        gap: 24px;
        min-height: auto;
    }

    .product-gallery {
        position: static;
        align-items: center;
    }

    .main-image {
        width: 300px;
        height: 300px;
    }

    .thumbnail-list {
        width: 300px;
    }

    .product-info {
        padding: 0;
        align-items: stretch;
    }

    .option-group {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }

    .option-label {
        padding-top: 0;
        min-width: auto;
    }

    .product-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }

    .product-title {
        font-size: 20px;
    }

    .price-value {
        font-size: 28px;
    }

    .action-buttons {
        flex-direction: column;
    }

    .shop-info-card {
        margin: 16px;
        padding: 16px;
    }

    .detail-tabs {
        padding: 0 16px;
    }

    .tab-item {
        padding: 12px 16px;
        font-size: 14px;
    }

    .detail-image {
        width: 95%;
        max-width: none;
    }
}
</style>
